package com.example.springwebonlyoffice.controller;

import cn.hutool.json.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;

@RestController
public class OfficeController {

    private Logger log = LoggerFactory.getLogger(getClass());

    private final Path rootLocation = Paths.get("office/");

    private static final String DOCUMENTS_DIR = "documents";

    @RequestMapping("/download")
    public ResponseEntity<Resource> download(HttpServletRequest request, HttpServletResponse response) {
        String fileDir = "office/";
        File file = new File(fileDir + "sql.xlsx");

        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        Resource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);

    }

    @RequestMapping(value = "/upload")
    public void upload(@RequestParam Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("11111111111111111111111111111");
        PrintWriter writer = null;
        String body = "";
        String attguid = request.getParameter("attguid");
        try {

            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream());
            scanner.useDelimiter("\\A");
            body = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
        } catch (Exception ex) {

            writer.write("get request.getInputStream error:" + ex.getMessage());
            return;
        }

        if (body.isEmpty()) {

            throw new RuntimeException("ONLYOFFICE回调保存请求体未空");
        }

        JSONObject jsonObj = new JSONObject(body);
        int status = (Integer) jsonObj.get("status");
        int saved = 0;
        String key = jsonObj.get("key").toString();
        if (status == 2 || status == 3 || status == 6) //MustSave, Corrupted
        {

            String downloadUri = (String) jsonObj.get("url");
            System.out.println(downloadUri);
            try {

                String filePath = "tempfiles/onlyoffice/savedownload/";
               /* FileUtil.initfloderPath(filePath);
                String fileName = CommonUtil.getNewGuid();
                HttpUtil.downLoadFromUrl(downloadUri, filePath, fileName);
                attachLogic.updateAttachContent(attguid, FileUtil.getBytes(filePath + fileName));*/
            } catch (Exception ex) {

                saved = 1;
                ex.printStackTrace();
            }
        }
        writer.write("{\"error\":" + saved + "}");
    }


}
